package com.hulk.redis;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.stereotype.Component;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Component("jedisPoolUtil")
public class JedisPoolUtil {
	// 本地异常日志记录对象
	private static final Logger logger = Logger.getLogger(JedisPoolUtil.class);

//	@Resource
	private static JedisConnectionFactory jedisConnectionFactory;
	
//	@Resource
	private static JedisPoolConfig poolConfig;

	private static JedisPool pool;

	public static Properties getJedisProperties() {

		Properties config = new Properties();
		InputStream is = null;
		try {
			is = JedisPoolUtil.class.getClassLoader().getResourceAsStream("cacheConfig.properties");
			config.load(is);
		} catch (IOException e) {
			logger.error("", e);
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					logger.error("", e);
				}
			}
		}
		return config;
	}

	/**
	 * 创建连接池
	 * 
	 */
	private static void createJedisPool() {
		// 建立连接池配置参数
		JedisPoolConfig config = jedisConnectionFactory.getPoolConfig();
		String host = jedisConnectionFactory.getHostName();
		int port = jedisConnectionFactory.getPort();
		int timeOut = jedisConnectionFactory.getTimeout();
		// 创建连接池
		pool = new JedisPool(config, host, port, timeOut);// 线程数量限制，IP地址，端口，超时时间
	}

	/**
	 * 在多线程环境同步初始化
	 */
	private static synchronized void poolInit() {
		if (pool == null)
			createJedisPool();
	}

	/**
	 * 获取一个jedis 对象
	 * 
	 * @return
	 */
	public static Jedis getJedis() {
		poolInit();
		return pool.getResource();
	}

	/**
	 * 释放一个连接
	 * 
	 * @param jedis
	 */
	public static void returnRes(Jedis jedis) {
		pool.returnResource(jedis);
	}

	/**
	 * 销毁一个连接
	 * 
	 * @param jedis
	 */
	public static void returnBrokenRes(Jedis jedis) {
		pool.returnBrokenResource(jedis);
	}
	
	
	public static void main(String[] args){
		Jedis jedis=getJedis();
		
	}

	public JedisConnectionFactory getJedisConnectionFactory() {
		return jedisConnectionFactory;
	}
	
	@Resource
	public void setJedisConnectionFactory(
			JedisConnectionFactory jedisConnectionFactory) {
		this.jedisConnectionFactory = jedisConnectionFactory;
	}

	public JedisPoolConfig getPoolConfig() {
		return poolConfig;
	}

	@Resource
	public void setPoolConfig(JedisPoolConfig poolConfig) {
		JedisPoolUtil.poolConfig = poolConfig;
	}

}
